<template>
  <div>
    <el-card class="search-card">
      <basic-form
        ref="formData"
        formItemWidth="150px"
        showColon
        defaultExpandStatus
        :formColumns="formItems"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        :handleClearForm="clearCategorySelect"
        @getFormData="getFormData"
      >
        <CategoryMultipleSelect
          slot="category"
          ref="categoryMultiple"
          @selectCategoryCallback="setFormCateUuids"
        />
      </basic-form>
    </el-card>
    <el-card class="table-card">
      <skus-table
        showSelectCol
        showActionCol
        :showPagination="isShowPagination"
        :tableHeight="480"
        :actionColWidth="200"
        :defaultMinWidth="100"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
        :loading="TableInfo.loading"
        :selectionChange="TableInfo.setSelection"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="total"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <BtnRender slot="content_context" :render="renderBtnsBar" />
      </skus-table>
    </el-card>
    <!-- 高级关联 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="updateTableListBySeniorLinked"
    />
    <!-- 修改日志查看 -->
    <EditLogViewDialog
      :visible.sync="editLog.visible"
      :sku-no="editLog.skuNo"
    />
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import CategoryMultipleSelect from '@/components/Category/MultipleSelect';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import EditLogViewDialog from './components/EditLogViewDialog';
import skusPage from '@/mixins/commodity/skusPage';
import { FORM_ITEMS, TABLE_COLUMNS } from './constants/list';
import { EDIT_UUIDS_KEY } from './constants/common';
import { getInitFormData, TableInfo } from '@/utils/getUtils';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { setAuthBtnId, createExcelByExport, generateUuid, isResponseSuccess, handleOpenNewPage } from '@/utils/bizUtils';
import {
  potentialSearchService,
  exportPotentialListService,
  valOpeDepartmentPermissionService,
  seniorLinkedSearchService
} from '@/api/commodity/temporaryPurchasingGoods/latentProduct';
export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    SkusTable,
    BtnRender,
    CategoryMultipleSelect,
    SeniorLinkedDialog,
    EditLogViewDialog,
  },
  data () {
    return {
      formItems: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS }),
      isShowPagination: true, // 是否展示分页，默认展示
      btnLoading: {
        edit: false, // 编辑loading
        export: false, // 导出loading
      },
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea' }],
        dataSource: [{ skuNo: '' }]
      },
      // 修改日志
      editLog: {
        visible: false,
        skuNo: ''
      },
      editLatentImage: {
        visible: false,
        skuInfo: {}
      },
      skuNos: [], // 高级关联的skuNos
    }
  },
  created () {
    this.initOpeHandler()
    this.handleQueryForm()
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const disabled = this.TableInfo.isNullSelection() // 按钮禁用属性
      const seniorBtn = {
        label: '高级查询',
        method: this.handleSeniorLinked,
        hasAuth: true,
        authLabel: '高级关联',
      }
      const exportBtn = {
        label: '导出',
        method: this.handleExport,
        loading: this.btnLoading.export,
        hasAuth: true
      }
      const batchEditBtn = {
        label: '批量编辑',
        method: this.handleBatchEdit,
        disabled,
        loading: this.btnLoading.edit,
        hasAuth: true
      }
      const finalBtns = [
        seniorBtn,
        exportBtn,
        batchEditBtn
      ]
      return getListPageBtnsBar(h, finalBtns, this.showBtn, 'start')
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '图文查看', method: this.handleViewImageText },
        { label: '图文编辑', method: this.handleEditImageText, hasAuth: true },
        { label: '修改日志', method: this.handleEditLog },
      ]
      return getTableAction({ h, row, actionList, showBtn: this.showBtn })
    },
    // 高级关联
    handleSeniorLinked () {
      this.seniorLinked.visible = true
    },
    // 导出
    async handleExport () {
      setAuthBtnId('导出')
      const data = { ...this.formData, skuNos: this.skuNos }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportPotentialListService(data, loadingFn)
      createExcelByExport({ res, excelTitle: `潜在商品_${generateUuid()}` })
    },
    // 批量编辑
    handleBatchEdit () {
      setAuthBtnId('批量编辑')
      this.validateCanEdit(uuids => {
        localStorage.setItem(EDIT_UUIDS_KEY, JSON.stringify(uuids))
        this.$router.push({ name: 'latentProductEdit' })
      })
    },
    // 图文查看
    handleViewImageText (row) {
      handleOpenNewPage(this, {
        name: 'latentProductImageText',
        query: {
          type: 'view',
          skuId: row.uuid,
          skuNo: row.skuNo,
        }
      })
    },
    // 图文编辑
    handleEditImageText (row) {
      setAuthBtnId('图文编辑')
      handleOpenNewPage(this, {
        name: 'latentProductImageText',
        query: {
          type: 'edit',
          skuId: row.uuid,
          skuNo: row.skuNo,
          isFromSourcing: this.$route?.query?.isFromSourcing
        }
      })
    },
    // 修改日志
    handleEditLog (row) {
      this.editLog.visible = true
      this.editLog.skuNo = row.skuNo
    },
    // 获取表格数据
    getTableData () {
      this.updateTableListByFormSearch()
    },
    // 更新表格集合数据 by 表单查询
    async updateTableListByFormSearch () {
      this.skuNos = [] // 普通查询清空高级关联skuNo集合
      setAuthBtnId('查询')
      this.isShowPagination = true
      const data = {
        ...this.formData,
        ...this.paginationParams
      }
      const res = await potentialSearchService(data, this.TableInfo.setLoading)
      this.TableInfo.setList(res?.retData?.results ?? [])
      this.setTotalNum(res?.retData?.totalNum ?? 0)
    },
    // 更新表格集合数据 by 高级查询
    async updateTableListBySeniorLinked (skuNos) {
      this.skuNos = skuNos
      setAuthBtnId('高级关联')
      this.isShowPagination = false
      const data = skuNos
      const res = await seniorLinkedSearchService(data, this.TableInfo.setLoading)
      this.TableInfo.setList(res?.retData ?? [])
    },
    // 校验能否编辑
    async validateCanEdit (onSuccess) {
      const uuids = this.TableInfo.selection.map(item => item.uuid)
      const loadingFn = state => { this.btnLoading.edit = state }
      const res = await valOpeDepartmentPermissionService(uuids, loadingFn)
      if (!isResponseSuccess(res)) return
      res?.retData.length == 0
       ? onSuccess(uuids)
       : this.$message(`商品${res.retData}不是您部门发起，您无权操作`)
    },
    // 初始操作
    initOpeHandler () {
      const skuNo = this.$route?.query?.skuNo
      if (skuNo) {
        this.formData.skuNo = skuNo
      }
    },
    // 获取关联品类信息
    setFormCateUuids (list) {
      this.formData.categoryUuids = list.map(item => item.categoryUuid)
    },
    // 清空品类选择信息
    clearCategorySelect () {
      this.$refs.categoryMultiple.clearSelectResult()
    },
  }
}
</script>
<style lang="less" scoped>
/deep/ .table-action {
  margin-right: 0;
}
</style>
